package uk.ac.lkl.common.ui;



import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;

import java.awt.event.*;
import javax.swing.*;


/**
 * A view that allows editing of its associated model through a
 * double-click.
 * 
 * @param the
 *            model
 * 
 * @author Darren Pearce
 * @version $Revision$
 * @version $Date$
 * 
 */
public abstract class EditingView<O> extends View<O> {

    private JLabel label;

    private JDialog dialog;

    // todo: re-use this - don't create one for each instance
    private ConfirmingEditor<O> editor;


    /**
     * 
     * @param view
     *            the view that will be used and double-clicks
     *            detected on
     * @param editor
     *            the component to produce on the screen when a
     *            double-click occurs on the view
     * @param model
     *            the model that the editor is editing
     */
    public EditingView(
                       View<O> view, Editor<O> editor, O model) {
        super(model);
        setLayout(new GridLayout(1, 1));
        this.editor = new ConfirmingEditor(editor);

        this.editor.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
            }
        });

        dialog = new JDialog();

        // todo: more work needed here to set title appropriately.
        dialog.setTitle("Edit");
        dialog.setResizable(false);
        add(view);

        addMouseListeners();
    }


    // todo: open dialog in center of screen always. Remember location
    // across calls? Allow dialog to stay up perhaps?
    private void addMouseListeners() {
        addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() < 2
                        || e.getButton() != MouseEvent.BUTTON1)
                    return;

                dialog.setContentPane(editor);
                dialog.pack();
                dialog.setModal(true);
                Rectangle bounds = getBounds();
                Point location = new Point(bounds.x, bounds.y + bounds.height);
                SwingUtilities.convertPointToScreen(location,
                                                    EditingView.this.getParent());
                dialog.setLocation(location);
                dialog.setVisible(true);
            }
        });
    }

}
